# BaseWeapon.gd (Can be Node2D or Area2D depending on weapon type)
class_name BaseWeapon
extends Node2D # Or Area2D for collision-based weapons

# Common weapon properties - Load from WeaponData or set per weapon script
var weapon_id: String = "base_weapon"
var damage: float = 5.0
var cooldown: float = 1.0
var range: float = 300.0 # Can mean different things: attack range, search range, projectile range
var quantity: int = 1 # Number of projectiles, axes, etc.

var player_node: Player = null # Reference to the player
var level: int = 1 # Current upgrade level of this specific weapon instance

@onready var cooldown_timer: Timer = Timer.new()

func _ready():
	add_child(cooldown_timer)
	cooldown_timer.wait_time = cooldown
	cooldown_timer.one_shot = true # Usually true for attack cooldowns
	cooldown_timer.timeout.connect(perform_attack) # Connect to the attack logic

	# Start the timer immediately? Or wait for first attack condition?
	# cooldown_timer.start()


func initialize(p_player: Player, data: WeaponData):
	player_node = p_player
	if data:
		weapon_id = data.weapon_id
		damage = data.base_damage
		cooldown = data.base_cooldown
		range = data.base_range
		# quantity might be handled differently (e.g., player script instantiates multiple)

	cooldown_timer.wait_time = cooldown
	print("Weapon Initialized:", weapon_id)
	# Start attacking if it's an auto-attack weapon
	if cooldown_timer.is_stopped():
		perform_attack()


func _physics_process(_delta):
	# Some weapons might need physics process (e.g., rotating axe)
	# Ensure it respects game pause state
	if GameManager.is_paused or GameManager.is_game_over:
		return
	pass


func find_nearest_enemy(search_range: float) -> Node2D:
	var nearest_enemy: Node2D = null
	var min_dist_sq = search_range * search_range

	# Assumes enemies are in the "enemies" group
	var enemies = get_tree().get_nodes_in_group("enemies")
	for enemy in enemies:
		if is_instance_valid(enemy) and enemy.has_method("is_dying") and not enemy.is_dying:
			var dist_sq = global_position.distance_squared_to(enemy.global_position)
			if dist_sq < min_dist_sq:
				min_dist_sq = dist_sq
				nearest_enemy = enemy
	return nearest_enemy


func perform_attack():
	# Base implementation does nothing - Override in specific weapon scripts
	# print(weapon_id, " attack triggered (base)")
	# Common pattern: Find target, fire projectile/activate effect, restart timer
	if cooldown > 0 and cooldown_timer.is_stopped(): # Check if timer needs restarting
		cooldown_timer.start()


func apply_upgrade(upgrade: WeaponUpgrade):
	level += 1
	match upgrade.upgrade_type:
		"damage":
			damage += upgrade.value_change # Or multiply: damage *= (1.0 + upgrade.value_change)
			print("%s damage upgraded to %f" % [weapon_id, damage])
		"speed":
			cooldown = max(0.1, cooldown - upgrade.value_change) # Decrease cooldown (increase speed), ensure minimum
			cooldown_timer.wait_time = cooldown
			print("%s cooldown reduced to %f" % [weapon_id, cooldown])
		"range":
			range += upgrade.value_change
			print("%s range increased to %f" % [weapon_id, range])
		"quantity":
			quantity = int(min(10, quantity + upgrade.value_change)) # Increase quantity, maybe cap it
			print("%s quantity increased to %d" % [weapon_id, quantity])
			# Quantity changes often need specific logic in perform_attack or Player script
		"special":
			# Implement special effect logic (e.g., set a boolean flag)
			# Example: 'pierce', 'bounce', 'burn'
			print("%s gained special effect: %s" % [weapon_id, upgrade.description])
			_apply_special_upgrade(upgrade)
		_:
			printerr("Unknown upgrade type '%s' for weapon '%s'" % [upgrade.upgrade_type, weapon_id])

	# Update internal state based on new stats if needed


func _apply_special_upgrade(_upgrade: WeaponUpgrade):
	# Placeholder for specific weapon special upgrade logic
	pass

# Required by enemy hurtbox check
func get_damage() -> float:
	# Could add randomness or other modifiers here
	return damage

# Called by enemy hurtbox after damage is applied
func on_hit_enemy(_enemy):
	# Placeholder for effects like removing pierce count, triggering bounce etc.
	pass